﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using System.Diagnostics.CodeAnalysis;
using TrackSystem.Entities.Dtos.Sensor;
using TrackSystem.Entities.Dtos.Var;
using TrackSystem.UI.Server.HttpRepository.Var;


namespace TrackSystem.UI.Server.Pages.Configuration
{
    /// <summary>
    /// 变量定义
    /// </summary>
    public partial class VarDefTable
    {
        /// <summary>
        /// 获得/设置 分页配置数据源
        /// </summary>
        private static IEnumerable<int> PageItemsSource => new int[] { 20, 30, 40 };

        private readonly IEnumerable<SelectedItem> _varSerialItem = new List<SelectedItem>()
        {
            new SelectedItem("Attr_Channel", "通道属性"),
            new SelectedItem("Sensor", "传感器"),
            new SelectedItem("Attr_Sensor", "传感器属性"),
            new SelectedItem("Loop", "回路"),
            new SelectedItem("Attr_Loop", "回路属性"),
            new SelectedItem("Attr_Logic", "逻辑属性"),
            new SelectedItem("Attr_Slave", "从站属性"),
            new SelectedItem("Attr_Record", "记录属性"),
            new SelectedItem("UserDefine", "用户自定义"),
        };

        private bool IsExeclMode { get; set; } = false;

        private void OnEditModeChanged()
        {
            IsExeclMode = !IsExeclMode;
            StateHasChanged();
        }

        [Inject]
        public IVarHttpRepository? repo { get; set; }

        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

        private async Task<QueryData<VarDto>> OnQueryAsync(QueryPageOptions options)
        {
            try
            {
                if (repo == null)
                {
                    await ToastService.Error("变量列表", "数据库未初始化");
                    return new QueryData<VarDto>();
                }

                var items = await repo.GetAll();

                items = items.Where(options.ToFilterFunc<VarDto>());

                // 排序
                var isSorted = false;
                if (!string.IsNullOrEmpty(options.SortName))
                {
                    items = items.Sort(options.SortName, options.SortOrder);
                    isSorted = true;
                }

                var total = items.Count();
                var result = new QueryData<VarDto>()
                {
                    Items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList(),
                    TotalCount = total,
                    IsFiltered = true,
                    IsSorted = isSorted,
                    IsSearch = true
                };

                return result;
            }
            catch (Exception)
            {
                return new QueryData<VarDto>
                {
                    Items = new List<VarDto>(),
                    TotalCount = 0,
                    IsFiltered = false,
                    IsSorted = false,
                    IsSearch = false
                };
            }
        }

        private async Task<bool> OnSaveAsync(VarDto snr, ItemChangedType changedType)
        {
            if (repo == null)
            {
                await ToastService.Error("变量列表", "数据库未初始化");
                return false;
            }

            var ret = false;
            if (changedType == ItemChangedType.Add)
            {
                var result = await repo.AddVar(snr);
                if (!result.Success)
                {
                    await ToastService.Error("变量列表", result.Message);
                }
                return result.Success;
            }
            else if (changedType == ItemChangedType.Update)
            {
                var result = await repo.UpdateVar(snr);
                if (!result.Success)
                {
                    await ToastService.Error("变量列表", result.Message);
                }
                return result.Success;
            }
            return ret;
        }

        private async Task<bool> OnDeleteAsync(IEnumerable<VarDto> snrs)
        {
            if (repo == null)
            {
                await ToastService.Error("变量列表", "数据库未初始化");
                return false;
            }

            bool ret = true;
            foreach (var item in snrs)
            {
                var result = await repo.DeleteVar(item.Id);
                if (result.Success)
                {
                    continue;
                }

                await ToastService.Error("变量列表", result.Message);
                ret = false;
            }

            return ret;
        }
    }
}
